<template>
  <view class="page custom-page">
    <custom-head gradient back title="创建积分项目">
      <view class="tool" slot="right">
        <!-- <i class="iconfont icon-fenlei fenlei" @click="show = true"></i> -->
        <!-- <i class="iconfont icon-fenlei fenlei" ></i>
        <text>删除</text> -->

        <view v-if="showDelete" class="rigth_icon" @click="show = true">
          <i class="iconfont icon-fenlei fenlei" ></i> 
          <view style="color: #fff;">删除</view>
        </view>
      </view>
    </custom-head>

    <view class="addition">
      <view class="touxiang-box flex col a-center j-c-c">
        <u-upload 
          max-count="1"
          action="/file/upload"
          :file-list="fileList"
          :form-data="{ type: 'avatar' }"
          :header="{ Authorization: token }"
          :action="BASE_URL + '/file/upload'"
          @on-change="onSuccess"
          @on-remove="omRemove"
        >
          <view class="touxiang" slot="addBtn">
            <image src="../../static/img/homeAdd01.png" mode="widthFix"></image>
          </view>
        </u-upload>
        <text>选择图标</text>
      </view>

      <view class="bottom_content">
        <view class="form">
          <u-form :model="form" ref="uForm" label-width="180" >
            <u-form-item label="名称" prop="name" :border-bottom="false" label-position="top" :label-style="{'fontSize': '30rpx', 'font-weight': '700'}">
              <u-input maxlength="9" v-model="form.title" placeholder="请输入名称 (10个字符内)" placeholderStyle="fontSize: 24rpx;fontWeight: 500;" />
            </u-form-item>

            <u-form-item label="分值" :border-bottom="false" label-position="top">
              <u-input type="number" v-model="form.cnt" placeholder="请输入分值，正数为添加积分，负数为减少积分" placeholderStyle="fontSize: 24rpx;fontWeight: 500;" />
            </u-form-item>

            <u-form-item label="分组" label-position="top">
              <u-input  v-model="form.group" placeholder="请输入分值，正数为添加积分，负数为减少积分" placeholderStyle="fontSize: 24rpx;fontWeight: 500;" />
            </u-form-item>

          </u-form>
        </view>

        <view class="button submit" @click="submit">保存</view>

        <u-modal :show-cancel-button="true" @confirm="confirm" v-model="show" content="确定要删除吗"></u-modal>

      </view>
    </view>
  </view>
</template>
<script>
import { BASE_URL } from '../../api/config';
import { addScore, getScoreDetail, updateScore, deleteScore } from "../../api/modules/score"

export default {
  data() {
    return {
      form: {
        title: '',
        cnt: '',
        group: '',
        icon: '',
      },
      rules: {},
      show: false,
      static_uri: getApp().globalData.glb_list.config.static_uri, // 获取全局配置文件
      BASE_URL,
      token: uni.getStorageSync('token'),
      fileList: [], // img
      showDelete: false, // 是否显示
    }
  },

  onReady() {
    this.$refs.uForm.setRules(this.rules)
  },

  mounted() {
    if (this.$route.query.id) {
      this.showDelete = true
      this._getScoreDetail(this.$route.query.id);
    }
  },

  methods: {
    confirm() {
      console.log('确定', this.$route.query.id)
      deleteScore(this.$route.query.id).then(res => {
        const { code } = res || {}
        if (code === 204) {
          this.$u.toast('删除成功');
          uni.navigateBack({
              delta: 1
          })
        }
      })
    },
    submit() {
      let data = {
        ...this.form,
        sid: this.glbId
      }
      this.$refs.uForm.validate(valid => {
        if (valid) {
          if (this.$route.query.id) {
            console.log('修改')
            this._updateScore(this.$route.query.id, data)
          } else { // 保存积分信息
            this._addScore(data)
          }
				} else {
					console.log('验证失败');
				}
			});
    },
    omRemove(index) { // 移除照片
			if (index === 0) {
				this.fileList = []
				this.form.icon = ''
			}
		},
    onSuccess(data) { // 上传照片
      const res = JSON.parse(data.data)
      if (res.code == 201) {
        this.form.icon = res.data.path
      } else {
        this.$refs.uUpload.clear()
        this.$u.toast('上传失败')
      }
    },
    _updateScore(id, data) { // 修改
      updateScore(id, data).then(res => {
        const { code, data } = res || {}
        if (code === 201) {
          this.$u.toast('修改成功')
          uni.navigateBack({
              delta: 1
          })
        }
      })
    },
    _getScoreDetail(id) { // 查看详情
      getScoreDetail(id).then(res => {
        const { code, data } = res || {}
        if (code === 200) {
          this.form = {
            ...data,
            group: data.group
          }
          this.fileList = [{url: `${this.static_uri}${data.icon}`}]
        }
        console.log('获取积分详情', data)
      })
    },
    _addScore(data) { // 添加积分
      addScore(data).then(res => {
        const { code } = res || {};
        if (code === 201) {
          this.$u.toast('添加成功')
          uni.navigateBack({
              delta: 1
          })
          this.form = {
            title: '',
            cnt: '',
            group: '',
            icon: '',
          }
        }
        // console.log('res 添加成功', res)
      })
    },
  }
}
</script>
<style scoped lang="scss">

.tool {
  width: 110rpx;
  .rigth_icon {
    display: flex;
  }
}
.touxiang-box {
  padding: 40rpx 0;
  font-size: 30rpx;
}

.touxiang {
  width: 150rpx !important;
  height: 150rpx !important;
  margin: auto;
  border-radius: 50%;
  overflow: hidden;
  margin-bottom: 25rpx;
}

.touxiang image {
  width: 100%;
  height: 100%;
}
.page {
  position: relative;
  height: 100vh;

  .addition {
    height: 100%;
  }
}

.bottom_content {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 0px 45rpx;
  height: calc(100% - 300rpx);
  background-color: #fff;
}
.form {
  background-color: #fff;
  
  overflow: hidden;
  /* height: 72vh; */
  font-weight: 700;
}

.button {
  width: 100%;
  height: 88rpx;
  border-radius: 44rpx;
  margin: 80rpx 0 40rpx 0;
  background-color: #2979ff;
  color: #fff;
  font-size: 32rpx;
  text-align: center;
  line-height: 88rpx;
}
/deep/ .u-form-item--left {
  align-items: self-start !important;
}
</style>
